package com.bawei.login.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.common.mvi.BaseViewModel
import com.bawei.login.LoginUiState
import com.bawei.login.LoginViewIntent
import com.bawei.login.repos.LoginRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(private val repository: LoginRepository): BaseViewModel<LoginViewIntent>(){
    private val _uiState = MutableStateFlow<LoginUiState>(LoginUiState.Empty)
    val uiState: StateFlow<LoginUiState> = _uiState
    override fun handIntent(uiIntent: LoginViewIntent) {
        when(uiIntent){
            is LoginViewIntent.LoginToServer -> loginToServer(uiIntent.userName, uiIntent.password)
        }
    }

    private fun loginToServer(userName: String, password: String){
        viewModelScope.launch {
            try {
                val result = repository.loginToServer(userName, password)
                if(result.code == 0){
                    _uiState.value = LoginUiState.LoginToServerSuccess(result.data)
                }else{
                    _uiState.value = LoginUiState.LoginToServerFail(result.msg)
                }
            } catch (e: Exception) {
                _uiState.value = LoginUiState.LoginToServerFail("请求接口异常")
            }
        }
    }


}